package org.dmikis.jmmengine.viewes;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import org.dmikis.jmmengine.controllers.ModelComputer;
import org.dmikis.jmmengine.models.Model;

/**
 * @author dmikis
 *
 * Class encapsulates creation of main application window.
 */    
@SuppressWarnings("serial")
public class MainFrame extends JFrame {

    public MainFrame(Model m, String title) {
	super();
	setTitle(title);
	setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HIEGHT);
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	addMouseListener(new PopupMenuExecutor());
	this.dialog = new ParametersDialog(m);
	this.computer = new ModelComputer(m);
	add(m.getResult().getVisualizationPanel(), BorderLayout.CENTER);
	add(this.computer.setStatusBar(new StatusBar()), BorderLayout.SOUTH);
	this.mainMenu = new JPopupMenu();
	JMenuItem menuItemParameters = new JMenuItem("Parameters");
	menuItemParameters.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		dialog.setVisible(true);
	    }
	});
	this.mainMenu.add(menuItemParameters);
	JMenuItem menuItemStart = new JMenuItem("Start");
	menuItemStart.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		try {
		    computer.start();
		}
		catch (Exception e) {
		    System.err.println(e.getMessage());
		}
	    }
	});
	this.mainMenu.add(menuItemStart);
	JMenuItem menuItemStop = new JMenuItem("Stop");
	menuItemStop.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent e) {
		computer.stop();
	    }
	});
	this.mainMenu.add(menuItemStop);
	JMenuItem menuItemExit = new JMenuItem("Exit");
	menuItemExit.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent arg0) {
		System.exit(0);
	    }
	});
	this.mainMenu.add(menuItemExit);
    }

    private JPopupMenu mainMenu;

    private ParametersDialog dialog;
    private ModelComputer computer;

    private static final int DEFAULT_FRAME_WIDTH = 640; // px
    private static final int DEFAULT_FRAME_HIEGHT = 480; // px

    /**
     * @author dmikis
     * @version 0.1
     * 
     * Class extends <code>MouseAdapter</code> to implement execution of the menu on click upon the main frame.
     */
    protected final class PopupMenuExecutor extends MouseAdapter {

	@Override
	public void mousePressed(MouseEvent arg0) {
	    if (mainMenu.isPopupTrigger(arg0)) {
		mainMenu.show(arg0.getComponent(), arg0.getX(), arg0.getY());
	    }
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
	    if (mainMenu.isPopupTrigger(arg0)) {
		mainMenu.show(arg0.getComponent(), arg0.getX(), arg0.getY());
	    }
	}
    }
}